﻿/*********************************************
 创建者：  曹亚亮
 创建时间：2017-10-14
 功能说明：订货会设置
 ********************************************/

using com.nm;
using com.nm.ApiServer;
using com.nm.ApiServer.Attributes;
using com.nm.Attributes;
using com.nm.db.Models.Systems;
using com.nm.library;
using EntityFramework.Extensions;
using System;
using System.Data;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using george.Data;
using static OrderAPI.Model.OrderMasterModel;

namespace OrderAPI
{
    [MustLogin]
    [Description("添加、修改、删除、查询订货会主表和子表数据信息")]
    public class OrderMasterHandler : BaseHandler
    {
        [MustLogin]
        [Description("获取订货会列表")]
        [ReturnType(typeof(PaperData<OrderMaster>))]
        public ApiResult GetOrderMasterList([ParamDescription("页码")]int Page = 1,[ParamDescription("页数")]int Size = 20)
        {
            try
            {
                if (string.IsNullOrEmpty(UserInfo.UserCompanyId))
                {
                    return Error("该用户不属于任何公司!");
                }
                if (string.IsNullOrEmpty(UserInfo.UserExtrSource))
                {
                    return Error("该用户所在公司没有任何数据源!");
                }

                var dc = new SysEntities();
                DateTime dt = DateTime.Now;
                var query = (from a in dc.t_order_master
                             where a.CompanyID == UserInfo.UserCompanyId && a.ExtrSource == UserInfo.UserExtrSource
                             select new
                             {
                                 a.MasterID,
                                 a.OrderName,
                                 OrderState = a.OrderFlag == true ? "已终止" : (dt < a.BeginDate ? "未开始" : (dt < a.EndDate ? "正在执行" : "已结束")),
                                 a.CreateDate
                             });
                var result = PaperData<OrderMaster>.Create(query.Count(), Size, Page);
                result.Items = query.OrderByDescending(t => t.CreateDate)
                          .Skip(result.Skip)
                          .Take(result.Limt).ToList()
                          .Select(o => new OrderMaster
                          {
                              MasterID = o.MasterID,
                              OrderName = o.OrderName,
                              OrderState = o.OrderState
                          }).ToList();
                return Success(result);
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }

        [MustLogin]
        [Description("获取订货会代码")]
        [ReturnType(typeof(string), "生成成功是订货会代码不为空")] //{"YearNo":2017,"SeasonName":"01","BandCode":1}
        public ApiResult GetOrderName([ParamDescription("年份")]int YearNo, [ParamDescription("季节")]string SeasonName, [ParamDescription("波段")]int BandCode)
        {
            try
            {
                #region 判断条件
                if (string.IsNullOrEmpty(UserInfo.UserCompanyId))
                {
                    return Error("该用户不属于任何公司!");
                }
                if (string.IsNullOrEmpty(UserInfo.UserExtrSource))
                {
                    return Error("该用户所在公司没有任何数据源!");
                }
                if (string.IsNullOrEmpty(YearNo.ToString()))
                {
                    return Error("年份不能为空");
                }
                if (string.IsNullOrEmpty(SeasonName))
                {
                    return Error("季节不能为空");
                }
                if (string.IsNullOrEmpty(BandCode.ToString()))
                {
                    return Error("波段不能为空");
                }
                #endregion

                var strOrderName = string.Empty;
                string strCompanyId = UserInfo.UserCompanyId;
                strOrderName = strCompanyId + YearNo.ToString() + SeasonName + BandCode.ToString() + "-"; //订货会代码前段

                strOrderName = NewOrderName(strOrderName);
                if (string.IsNullOrEmpty(strOrderName))
                {
                    return Error("订货会代码生成失败");
                }

                return Success(strOrderName);
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }

        //public ApiResult InsertOrderMaster([ParamDescription("年份")]int YearNo, [ParamDescription("季节")]string SeasonName, [ParamDescription("波段")]int BandCode, [ParamDescription("开始日期")]DateTime BeginDate, [ParamDescription("结束日期")]DateTime EndDate, [ParamDescription("是否终止")]bool OrderFlag=false)
        [Description("保存选版人员评分权重")]
        [MustLogin]
        [JsonType]
        [ReturnType(typeof(int), "大于0时成功返回新增数据的MasterID")]//{"YearNo":2017,"SeasonName":"01","BandCode":1,"BeginDate":"2017-10-16","EndDate":"2017-10-19","OrderFlag":false,"list":[{"GradeName":"流行度","GradeRate":0.26}]}
        public ApiResult InsertOrderMaster([ParamDescription("参数实体类")] OrderMasterInsert param)
        {
            try
            {
                #region 判断条件
                if (param == null || param.list.Count == 0) return Error("参数行不能为空");
                if (string.IsNullOrEmpty(UserInfo.UserCompanyId))
                {
                    return Error("该用户不属于任何公司!");
                }
                if (string.IsNullOrEmpty(UserInfo.UserExtrSource))
                {
                    return Error("该用户所在公司没有任何数据源!");
                }
                if (string.IsNullOrEmpty(param.YearNo.ToString()))
                {
                    return Error("年份不能为空");
                }
                if (string.IsNullOrEmpty(param.SeasonName))
                {
                    return Error("季节不能为空");
                }
                if (string.IsNullOrEmpty(param.BandCode.ToString()))
                {
                    return Error("波段不能为空");
                }
                if (string.IsNullOrEmpty(param.BeginDate.ToString()))
                {
                    return Error("开始时间不能为空");
                }
                if (string.IsNullOrEmpty(param.EndDate.ToString()))
                {
                    return Error("结束时间不能为空");
                }
                #endregion
                
                var strOrderName = string.Empty;
                var strOrderID = string.Empty;
                string strCompanyId = UserInfo.UserCompanyId;
                string strExtrSource = UserInfo.UserExtrSource;
                strOrderName = strCompanyId + param.YearNo.ToString() + param.SeasonName + param.BandCode.ToString() + "-"; //订货会代码前段
                strOrderName = NewOrderName(strOrderName);
                strOrderID = NewOrderID(strCompanyId);
                if (!string.IsNullOrEmpty(strOrderName) && !string.IsNullOrEmpty(strOrderID))
                {
                    var dc = new SysEntities();
                    var data = new t_order_master
                    {
                        CompanyID = strCompanyId,
                        ExtrSource = strExtrSource,
                        OrderName = strOrderName,
                        OrderID = strOrderID,
                        YearNo = param.YearNo,
                        SeasonName = param.SeasonName,
                        BandCode = param.BandCode,
                        BeginDate = param.BeginDate,
                        EndDate = param.EndDate,
                        OrderFlag = param.OrderFlag,
                        Remark = "",
                        CreateDate = DateTime.Now,
                        Creator = this.UserId
                    };
                    dc.t_order_master.Add(data);
                    int num = dc.SaveChanges();
                    if (num > 0)
                    {
                        InsertOrderGradeDetail(data.MasterID, param.list);
                    }
                    
                    return Success(data.MasterID);
                }
                else
                {
                    return Error("新增订货会信息失败！");
                }
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }
        
        [MustLogin]
        [Description("删除订货会信息")]
        [ReturnType(typeof(int), "0-成功")] //{"MasterID":2}
        public ApiResult DeleteOrderMaster([ParamDescription("订货会内码ID")]int MasterID)
        {
            if (MasterID == 0)
            {
                return Error("订货会内码ID不能为0");
            }

            //using (var dc = new SysEntities())
            //{
            //    var tran = dc.Database.BeginTransaction();  //开启事务
            //    try
            //    {
            //        dc.t_order_SKCRequire.Where(a => a.MasterID == MasterID).Delete();
            //        dc.t_order_styledetail.Where(a => a.MasterID == MasterID).Delete();
            //        dc.t_order_master.Where(a => a.MasterID == MasterID).Delete();
            //        tran.Commit();  //提交处理请求
            //        return Success(0);
            //    }
            //    catch (Exception ex)
            //    {
            //        tran.Rollback();  //出错就回滚
            //        return Error(ex);
            //    }
            //}

            try
            {
                using (var dc = new SysEntities())
                {
                    
                    dc.t_order_SKCRequire.Where(a => a.MasterID == MasterID).Delete();
                    dc.t_order_styledetail.Where(a => a.MasterID == MasterID).Delete();
                    dc.t_order_GradeDetail.Where(a => a.MasterID == MasterID).Delete();
                    dc.t_order_master.Where(a => a.MasterID == MasterID).Delete();
                }
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
            return Success(0);
        }


        //public ApiResult UpdateOrderMaster([ParamDescription("订货会内码ID")]int MasterID,[ParamDescription("开始日期")]DateTime BeginDate,[ParamDescription("结束日期")]DateTime EndDate,[ParamDescription("是否终止")]bool OrderFlag = false)
        [Description("修改订货会信息")]
        [MustLogin]
        [JsonType]
        [ReturnType(typeof(int), "0-成功")] //{"MasterID":2,"BeginDate":"2017-10-16","EndDate":"2017-10-19","OrderFlag":false,"list":[{"GradeName":"流行度","GradeRate":0.26}]}
        public ApiResult UpdateOrderMaster([ParamDescription("参数实体类")] OrderMasterUpdate param)
        {
            try
            {
                if (param == null || param.list.Count == 0) return Error("参数行不能为空");
                if (param.MasterID == 0)
                {
                    return Error("订货会内码ID不能为0");
                }
                if (string.IsNullOrEmpty(param.BeginDate.ToString()))
                {
                    return Error("开始时间不能为空");
                }
                if (string.IsNullOrEmpty(param.EndDate.ToString()))
                {
                    return Error("结束时间不能为空");
                }
                
                using (var dc = new SysEntities())
                {
                    var data = dc.t_order_master.FirstOrDefault(s => s.MasterID == param.MasterID);
                    if (data != null)
                    {
                        data.BeginDate = param.BeginDate;
                        data.EndDate = param.EndDate;
                        data.OrderFlag = param.OrderFlag;

                        int num = dc.SaveChanges();
                        if (num > 0)
                        {
                            InsertOrderGradeDetail(param.MasterID, param.list);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
            return Success(0);
        }

        //保存评分项信息
        public void InsertOrderGradeDetail(int MasterID, IList<OrderGradeDetail> list)
        {
            var dc = new SysEntities();
            dc.t_order_GradeDetail.Where(a => a.MasterID == MasterID).Delete();
            int Creator = this.UserId;
            string ExtrSource = UserInfo.UserExtrSource;
            string CompanyID = UserInfo.UserCompanyId;
            DateTime CreateDate = DateTime.Now;
            foreach (var item in list)
            {

                var data = new t_order_GradeDetail
                {
                    ExtrSource = ExtrSource,
                    CompanyID = CompanyID,
                    MasterID = MasterID,
                    GradeName = item.GradeName,
                    GradeRate = item.GradeRate,
                    CreateDate = CreateDate,
                    Creator = Creator
                };
                dc.t_order_GradeDetail.Add(data);
            }
            dc.SaveChanges();
        }

        [MustLogin]
        [Description("获取订货需求列表")]
        [ReturnType(typeof(PaperData<OrderSKCRequire>))] //{"MasterID":2}
        public ApiResult GetOrderSKCRequireList([ParamDescription("订货会内码ID")]int MasterID, [ParamDescription("页码")]int Page = 1, [ParamDescription("页数")]int Size = 20)
        {
            try
            {
                if (string.IsNullOrEmpty(UserInfo.UserCompanyId))
                {
                    return Error("该用户不属于任何公司!");
                }
                if (string.IsNullOrEmpty(UserInfo.UserExtrSource))
                {
                    return Error("该用户所在公司没有任何数据源!");
                }
                if (MasterID == 0)
                {
                    return Error("订货会内码ID不能为0");
                }

                var dc = new SysEntities();
                var query = dc.t_order_SKCRequire.Where(a => a.MasterID == MasterID);

                var result = PaperData<OrderSKCRequire>.Create(query.Count(), Size, Page);
                result.Items = query.OrderBy(t => t.CreateDate)
                          .Skip(result.Skip)
                          .Take(result.Limt).ToList()
                          .Select(o => new OrderSKCRequire
                          {
                              RequireID = o.RequireID,
                              SerialName = o.SerialName,
                              MaterialProperty = o.MaterialProperty,
                              ItemName = o.ItemName,
                              SKCQty = o.SKCQty
                          }).ToList();
                return Success(result);
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }

        [MustLogin]
        [Description("删除订货需求信息")]
        [ReturnType(typeof(int), "0-成功")] //{"RequireID":2}
        public ApiResult DeleteOrderSKCRequire([ParamDescription("订货需求内码ID")]int RequireID)
        {
            try
            {
                if (RequireID == 0)
                {
                    return Error("订货需求内码ID不能为0");
                }
                using (var dc = new SysEntities())
                {
                    dc.t_order_SKCRequire.Where(a => a.RequireID == RequireID).Delete();
                }
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
            return Success(0);
        }

        [MustLogin]
        [Description("获取款号设置列表")]
        [ReturnType(typeof(PaperData<OrderStyleDetail>))] //{"MasterID":2}
        public ApiResult GetOrderStyleDetailList([ParamDescription("订货会内码ID")]int MasterID, [ParamDescription("页码")]int Page = 1, [ParamDescription("页数")]int Size = 20)
        {
            try
            {
                if (string.IsNullOrEmpty(UserInfo.UserCompanyId))
                {
                    return Error("该用户不属于任何公司!");
                }
                if (string.IsNullOrEmpty(UserInfo.UserExtrSource))
                {
                    return Error("该用户所在公司没有任何数据源!");
                }
                if (MasterID == 0)
                {
                    return Error("订货会内码ID不能为0");
                }

                var dc = new SysEntities();
                var query = dc.t_order_styledetail.Where(a => a.MasterID == MasterID);

                var result = PaperData<OrderStyleDetail>.Create(query.Count(), Size, Page);
                result.Items = query.OrderBy(t => t.CreateDate)
                          .Skip(result.Skip)
                          .Take(result.Limt).ToList()
                          .Select(o => new OrderStyleDetail
                          {
                              DetailID = o.DetailID,
                              SerialNo = o.SerialNo,
                              DesignNo = o.DesignNo,
                              ColorCode = o.ColorCode,
                              ShortName = o.ShortName,
                              OrderType = o.OrderType,
                              YearNo = o.YearNo,
                              SeasonName = o.SeasonName,
                              Category = o.Category,
                              SerialName = o.SerialName,
                              MaterialProperty = o.MaterialProperty,
                              ModelName = o.ModelName,
                              ItemName = o.ItemName,
                              CollarTypeName = o.CollarTypeName,
                              ClothesVersionName = o.ClothesVersionName,
                              OrderAttribName = o.OrderAttribName,
                              VendCustCode = o.VendCustCode,
                              VendCustName = o.VendCustName,
                              DesignName = o.DesignName,
                              ElementName = o.ElementName,
                              CommodityProfileName = o.CommodityProfileName,
                              ThicknessName = o.ThicknessName,
                              IsModelStyle = o.IsModelStyle,
                              Waistband = o.Waistband,
                              CostPrice = o.CostPrice,
                              OrderRate = o.OrderRate,
                              RetailPrice = o.RetailPrice,
                              StuffType = o.StuffType,
                              StuffName = o.StuffName,
                              Lining = o.Lining,
                              Filling = o.Filling,
                              SaleDate = o.SaleDate,
                              Remark = o.Remark
                          }).ToList();
                return Success(result);
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }

        [MustLogin]
        [Description("删除款号设置信息")]
        [ReturnType(typeof(int), "0-成功")] //{"DetailID":2}
        public ApiResult DeleteOrderStyleDetail([ParamDescription("款号设置内码ID")]int DetailID)
        {
            try
            {
                if (DetailID == 0)
                {
                    return Error("款号设置内码ID不能为0");
                }
                using (var dc = new SysEntities())
                {
                    dc.t_order_styledetail.Where(a => a.DetailID == DetailID).Delete();
                }
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
            return Success(0);
        }

        [MustLogin]
        [Description("获取订货会评分列表")]
        [ReturnType(typeof(IList<OrderGradeDetail>))] //{"MasterID":2}
        public ApiResult GetOrderGradeDetailList([ParamDescription("订货会内码ID")]int MasterID)
        {
            try
            {
                if (MasterID == 0)
                {
                    return Error("订货会内码ID不能为0");
                }

                var dc = new SysEntities();

                var query = from o in dc.t_order_GradeDetail
                            where o.MasterID == MasterID
                            select o;
                var result = query.ToList().Select(t => new OrderGradeDetail
                {
                    GradeName = t.GradeName,
                    GradeRate = t.GradeRate
                }).ToList();
                return Success(result);
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }

        //生成新的订货会代码
        public string NewOrderName(string OrderNamePrefix)
        {
            try
            {
                string strOrderName = string.Empty;
                var dc = new SysEntities();
                var query = (from a in dc.t_order_master where a.OrderName.Contains(OrderNamePrefix) select a).OrderByDescending(a => a.OrderName).FirstOrDefault();
                if (query == null)
                {
                    strOrderName = OrderNamePrefix + "0001";
                }
                else
                {
                    var intNum = Convert.ToInt32(query.OrderName.Split('-')[1].ToString()) + 1;
                    strOrderName = OrderNamePrefix + intNum.ToString().PadLeft(4, '0');
                }
                return strOrderName;
            }
            catch
            {
                return "";
            }
        }

        //生成新的订货会流水号
        public string NewOrderID(string CompanyId)
        {
            try
            {
                string strOrderID = string.Empty;
                var dc = new SysEntities();
                var query = (from a in dc.t_order_master select a).OrderByDescending(a => a.OrderID).FirstOrDefault();
                if (query != null)
                {
                    var intNum = Convert.ToInt32(query.OrderID.Replace(CompanyId, "")) + 1;
                    strOrderID = CompanyId + intNum.ToString().PadLeft(6, '0');
                }
                else
                {
                    strOrderID = CompanyId + "000001";
                }
                return strOrderID;
            }
            catch
            {
                return "";
            }
        }

        //导入订货需求信息
        public void ImportOrderSKCRequire(DataTable dt, int MasterID)
        {
            try
            {
                var dc = new SysEntities();
                int Creator = this.UserId;
                string ExtrSource = UserInfo.UserExtrSource;
                string CompanyID = UserInfo.UserCompanyId;
                DateTime CreateDate = DateTime.Now;
                foreach (DataRow item in dt.Rows)
                {
                    #region 校验

                    var gsCode = item["SKCQty"].ToString();
                    int id = 0;
                    if (!int.TryParse(gsCode, out id))
                    {
                        continue;
                    }
                    #endregion

                    var data = new t_order_SKCRequire
                    {
                        Creator = Creator,
                        ExtrSource = ExtrSource,
                        CompanyID = CompanyID,
                        CreateDate = CreateDate,
                        MasterID = MasterID,
                        SerialName = item["SerialName"].ToString(),
                        MaterialProperty = item["MaterialProperty"].ToString(),
                        ItemName = item["ItemName"].ToString(),
                        SKCQty = Convert.ToInt32(item["SKCQty"].ToString())
                    };

                    dc.t_order_SKCRequire.Add(data);
                }
                dc.SaveChanges();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //导入款号设置信息
        public void ImportOrderStyleDetail(DataTable dt, int MasterID)
        {
            try
            {
                var dc = new SysEntities();
                int Creator = this.UserId;
                string ExtrSource = UserInfo.UserExtrSource;
                string CompanyID = UserInfo.UserCompanyId;
                DateTime CreateDate = DateTime.Now;
                foreach (DataRow item in dt.Rows)
                {
                    var data = new t_order_styledetail
                    {
                        ExtrSource = ExtrSource,
                        Creator = Creator,
                        CompanyID = CompanyID,
                        CreateDate = CreateDate,
                        MasterID = MasterID,
                        SerialNo = item["SerialNo"].ToString(),
                        DesignNo = item["DesignNo"].ToString(),
                        ColorCode = item["ColorCode"].ToString(),
                        ColorName = item["ColorName"].ToString(),
                        ShortName = item["ShortName"].ToString(),
                        OrderType = item["OrderType"].ToString(),
                        YearNo = Convert.ToInt32(item["YearNo"].ToString()),
                        SeasonName = item["SeasonName"].ToString(),
                        Category = item["Category"].ToString(),
                        SerialName = item["SerialName"].ToString(),
                        MaterialProperty = item["MaterialProperty"].ToString(),
                        ModelName = item["ModelName"].ToString(),
                        ItemName = item["ItemName"].ToString(),

                        CollarTypeName = item["CollarTypeName"].ToString(),
                        ClothesVersionName = item["ClothesVersionName"].ToString(),
                        OrderAttribName = item["OrderAttribName"].ToString(),
                        VendCustCode = item["VendCustCode"].ToString(),
                        VendCustName = item["VendCustName"].ToString(),
                        DesignName = item["DesignName"].ToString(),
                        ElementName = item["ElementName"].ToString(),
                        CommodityProfileName = item["CommodityProfileName"].ToString(),
                        ThicknessName = item["ThicknessName"].ToString(),
                        IsModelStyle = item["IsModelStyle"].ToString(),
                        Waistband = item["Waistband"].ToString(),
                        CostPrice = Convert.ToDecimal(item["CostPrice"].ToString()),
                        OrderRate = Convert.ToDecimal(item["OrderRate"].ToString()),
                        RetailPrice = Convert.ToDecimal(item["RetailPrice"].ToString()),
                        StuffType = item["StuffType"].ToString(),
                        StuffName = item["StuffName"].ToString(),
                        Lining = item["Lining"].ToString(),
                        Filling = item["Filling"].ToString(),
                        SaleDate = Convert.ToDateTime(item["SaleDate"].ToString())
                    };

                    dc.t_order_styledetail.Add(data);
                }
                dc.SaveChanges();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
